package org.jeecg.modules.arc.service.impl;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.YouBianCodeUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.mybatis.TenantContext;
import org.jeecg.modules.arc.entity.ArcAccount;
import org.jeecg.modules.arc.entity.ArcAccountMeter;
import org.jeecg.modules.arc.entity.ArcContacts;
import org.jeecg.modules.arc.entity.ArcCustomers;
import org.jeecg.modules.arc.mapper.ArcCustomersMapper;
import org.jeecg.modules.arc.service.IArcAccountMeterService;
import org.jeecg.modules.arc.service.IArcAccountService;
import org.jeecg.modules.arc.service.IArcContactsService;
import org.jeecg.modules.arc.service.IArcCustomersService;
import org.jeecg.modules.arc.vo.ArcIndexDataVO;
import org.jeecg.modules.chg.entity.ChgArrears;
import org.jeecg.modules.chg.service.IChgArrearsService;
import org.jeecg.modules.chg.service.IChgFeesService;
import org.jeecg.modules.mr.entity.MrBookMeters;
import org.jeecg.modules.mr.entity.MrUnread;
import org.jeecg.modules.mr.service.IMrBookMetersService;
import org.jeecg.modules.mr.service.IMrRecordsService;
import org.jeecg.modules.mr.service.IMrUnreadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * @Description: 用户水表
 * @Author: jeecg-boot
 * @Date:   2022-02-07
 * @Version: V1.0
 */
@Service
public class ArcCustomersServiceImpl extends ServiceImpl<ArcCustomersMapper, ArcCustomers> implements IArcCustomersService {

    @Autowired
    private ArcCustomersMapper arcCustomersMapper;
    @Autowired
    private IArcAccountService accountService;
    @Autowired
    private IArcAccountMeterService accountMeterService;
    @Autowired
    private IArcContactsService contactsService;
    @Autowired
    private IMrBookMetersService bookMetersService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private IMrRecordsService recordsService;
    @Autowired
    private IArcCustomersService customersService;
    @Autowired
    private IChgFeesService chgFeesService;
    @Autowired
    private IChgArrearsService chgArrearsService;
    @Autowired
    private IMrUnreadService unreadService;
    @Autowired
    private RedisUtil redisUtil;


    @Override
    @Transactional
    public Result<?> saveAccount(JSONObject cusObj) throws ParseException {
        String msg="";
        if(null != cusObj
                && null != cusObj.get("formData1")
                && null != cusObj.get("formData2")
                && null != cusObj.get("formData3")
                && null != cusObj.get("formData4") ) {
            cusObj = (JSONObject) JSONObject.parse(JSON.toJSONString(cusObj));

            msg = checkFormData(cusObj);
            if(msg.length()>5){
                return Result.error(msg);
            }
            //用户信息
            JSONObject formData1 = (JSONObject) cusObj.get("formData1");
            JSONObject formData2 = (JSONObject) cusObj.get("formData2");
            JSONObject formData3 = (JSONObject) cusObj.get("formData3");
            JSONObject formData4 = (JSONObject) cusObj.get("formData4");

            String contactsId="";
            ArcCustomers arcCustomers = new ArcCustomers();
            if(oConvertUtils.isNotEmpty(formData1.getString("contactId"))){
                //有用户档案ID\ 无需 其他用户信息
                arcCustomers.setContactId(formData1.getString("contactId"));
                arcCustomers.setCusName(formData1.getString("name"));
                contactsId=arcCustomers.getContactId();
            }else{
                //先保存 用户档案 获取ID
                ArcContacts contacts = new ArcContacts();
                contacts.setName(formData1.getString("name"));
                contacts.setAddress(formData1.getString("address"));
                contacts.setCertificateId(formData1.getString("certificateId"));
                contacts.setCertificateType(formData1.getString("certificateType"));
                contacts.setEmail(formData1.getString("email"));
                contacts.setMobile(formData1.getString("mobile"));
                contacts.setPostcode(formData1.getString("postcode"));
                contacts.setPinyin(PinyinUtil.getFirstLetter(contacts.getName(), ""));
                contactsService.save(contacts);
                arcCustomers.setContactId(contacts.getId());
                arcCustomers.setCusName(contacts.getName());
                contactsId=contacts.getId();
            }
            /** 水表信息*/
            arcCustomers.setCode(formData2.getString("code"));

            /**验证编码是否存在*/
            Integer count = arcCustomersMapper.selectCount(new LambdaQueryWrapper<ArcCustomers>()
                    .eq(ArcCustomers::getCode, arcCustomers.getCode())
                    .eq(ArcCustomers::getDelFlag, 0));
            if(count>0){
                //存在，重新获取
                String nextBianCode ="";
                List<ArcCustomers> customersList = arcCustomersMapper.selectList(
                        new LambdaQueryWrapper<ArcCustomers>()
                        .eq(ArcCustomers::getDelFlag, 0)
                        .orderByDesc(ArcCustomers::getCode));
                if(null != customersList && customersList.size()>0){
                    String code = customersList.get(0).getCode();
                    nextBianCode = YouBianCodeUtil.getNextBianCode("", code, code.length());
                }else{
                    nextBianCode = YouBianCodeUtil.getNextBianCode("", "020001", 6);
                }
                arcCustomers.setCode(nextBianCode);
            }

            arcCustomers.setAreaId(formData2.getString("areaId"));
            arcCustomers.setWaterUserStatus(formData2.getString("waterUserStatus"));
            arcCustomers.setGroupname(formData2.getString("groupname"));
            arcCustomers.setAddress(formData2.getString("address"));
            Date EnabledTime = oConvertUtils.isNotEmpty(formData2.getString("enabledTime")) ? DateUtils.parseDate(formData2.getString("enabledTime"),"yyyy-MM-dd") :null;
            arcCustomers.setEnabledTime(EnabledTime );
            arcCustomers.setFirstInstallTime(DateUtils.parseDate(formData2.getString("firstInstallTime"),"yyyy-MM-dd") );
            arcCustomers.setIsRemote(formData2.getInteger("isRemote"));
            arcCustomers.setWaterUseType(formData2.getString("waterUseType"));
            arcCustomers.setWaterPressurLevel(formData2.getString("waterPressurLevel"));
            arcCustomers.setWaterCaliberSize(formData2.getString("waterCaliberSize"));
            arcCustomers.setManholeId(formData2.getString("manholeId"));

            /**计费信息  * \\\\\\*/
            arcCustomers.setNatureId(formData3.getString("natureId"));
            arcCustomers.setIsCalculated(formData3.getInteger("isCalculated"));
            arcCustomers.setIsCharged(formData3.getInteger("isCharged"));
            arcCustomers.setIsStored(formData3.getInteger("isStored"));
            arcCustomers.setIsVat(formData3.getInteger("isVat"));
            arcCustomers.setIsPreinvoiced(formData3.getInteger("isPreinvoiced"));
            arcCustomers.setIsTieredPrice(formData3.getInteger("isTieredPrice"));
            /**抄表信息   \\\\firstScale\paidDay */
            arcCustomers.setWaterReadCycle(formData4.getString("waterReadCycle"));
            arcCustomers.setBookId(formData4.getString("bookId"));
            arcCustomers.setPaidDay(formData4.getString("paidDay"));
            arcCustomers.setIsRead(formData4.getInteger("isRead"));
            arcCustomers.setReadTimes(formData4.getInteger("readTimes"));
            arcCustomers.setUnreadTimes(formData4.getInteger("unreadTimes"));
            arcCustomers.setFirstScale(new BigDecimal(formData4.getString("firstScale")));
            arcCustomers.setLastReadScale(arcCustomers.getFirstScale());
            arcCustomersMapper.insert(arcCustomers);

            //创建缴费账户
            ArcAccount arcAccount = new ArcAccount();
            arcAccount.setContactId(arcCustomers.getContactId());
            arcAccount.setBalance(new BigDecimal(0.0));
            arcAccount.setCode(arcCustomers.getCode());
            arcAccount.setFeeCusType("1");
            arcAccount.setIsStored(arcCustomers.getIsStored());
            arcAccount.setIsVat(arcCustomers.getIsVat());
            arcAccount.setIsPreInvoiced(arcCustomers.getIsPreinvoiced());
            arcAccount.setWaterUserStatus(arcCustomers.getWaterUserStatus());
            arcAccount.setStatus(1);
            arcAccount.setCode(arcCustomers.getCode());
            accountService.save(arcAccount);

            ArcAccountMeter accountMeter = new ArcAccountMeter();
            accountMeter.setAccountId(arcAccount.getId());
            accountMeter.setCusId(arcCustomers.getCode());//直接编号
            accountMeter.setStatus(1);
            accountMeterService.save(accountMeter);

            //用户档案绑定缴费账号编号
            contactsService.update(new LambdaUpdateWrapper<ArcContacts>()
                    .set(ArcContacts::getCode,arcAccount.getCode()).eq(ArcContacts::getId,contactsId));

            //抄表本关联
            MrBookMeters mrBookMeters = new MrBookMeters();
            mrBookMeters.setBookId(arcCustomers.getBookId());
            mrBookMeters.setCustomerId(arcCustomers.getCode());
            mrBookMeters.setCusName(arcCustomers.getCusName());
            mrBookMeters.setOrderNo(1);
            bookMetersService.save(mrBookMeters);

            /**设置首页数据动态更新-退费*/
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        chgFeesService.indexData(null,null);;
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        log.warn("首页数据动态更新");
                    }
                }
            }).start();
            String tenant = TenantContext.getTenant();
            String key="arc::next::code::"+tenant;
            redisUtil.set(key,arcCustomers.getCode());
        }
        msg="开户成功";
        return Result.error(msg);
    }

    @Override
    public void readMonthInit() {
        /**
         * 需要测试-多租户问题
         *
         * 抄表周期
         * 每月	1
         * 单月	2
         * 双月	3
         * 季度上	4
         * 季度中	5
         * 季度下	6
         * 半年	7
         * 一月多抄 8
         *
         * 用水状态
         * 未启用	0
         * 正常	1
         * 报停	2
         * 停水	3
         * 锁定	4
         *
         * */

        //当前月份
        Calendar calendar = DateUtils.getCalendar();
        int m = calendar.get(Calendar.MONTH)+1; //从0开始

        //满足的抄表周期
        List<Integer>readMonth=new ArrayList<>();

        if( m % 6 == 0){
            //半年
            readMonth.add(7);
        }
        if( m % 3 == 0){
            //季度下
            readMonth.add(6);
        }else if( m % 3 == 2){
            //季度中
            readMonth.add(5);
        }else if( m % 3 == 1){
            //季度上
            readMonth.add(4);
        }

        if( m % 2 == 0){
            //双月
            readMonth.add(3);
        }else{
            //单月
            readMonth.add(2);
        }
        //每月
        readMonth.add(1);
        //一月多抄 有次数直接走SQL
//        readMonth.add(8);

        ////需要变量多租户
        //List<TenantModel> tenantList = sysBaseAPI.queryTenant();
        //if(null != tenantList && tenantList.size()>0) {
        //    //遍历租户
        //    for (TenantModel tenantModel : tenantList) {
        //        TenantContext.setTenant(tenantModel.getId() + "");

                //查询本月未抄的 下月1号执行的
                List<ArcCustomers> unCusLs = arcCustomersMapper.selectList(new LambdaQueryWrapper<ArcCustomers>()
                        .eq(ArcCustomers::getDelFlag, 0)
                        .eq(ArcCustomers::getWaterUserStatus, "1") //正常
                        .gt(ArcCustomers::getUnreadTimes, 0) //待抄次数>0 即视为未抄
                        );
                //所以抄表月份是上月
                Calendar calendarMonth = DateUtils.getCalendar();
                calendarMonth.add(Calendar.MONTH,-1);
                Date readDate = calendarMonth.getTime();

                if(null != unCusLs && unCusLs.size()>0){
                    for (ArcCustomers customers : unCusLs) {

                        //定时任务-online插入方式异常-没有登录用户
                        //MrUnread mrUnread = new MrUnread();
                        //mrUnread.setReadMonth(DateUtils.formatDate(readDate,"yyyyMM"));
                        //mrUnread.setCustomerId(customers.getId());
                        //mrUnread.setCusName(customers.getCusName());
                        //mrUnread.setCusName(customers.getCusName());
                        //mrUnread.setWaterReadCycle(customers.getWaterReadCycle());
                        //mrUnread.setUnreadTimes(customers.getUnreadTimes());
                        //mrUnread.setReadTimes(customers.getReadTimes());
                        //mrUnread.setTenantId(customers.getTenantId());
                        //unreadService.save(mrUnread);

                        //抄见未抄记录 当前月份是上个月的
                        //String unReadCode="402881a97ebab91e017ebb1ff1140006";
                        //
                        //JSONObject jsonUnRead=new JSONObject();
                        ////jsonUnRead.put("book_id",customers.get);
                        //jsonUnRead.put("read_month",DateUtils.formatDate(readDate,"yyyyMM"));
                        //jsonUnRead.put("customer_id",customers.getId());
                        //jsonUnRead.put("cus_name",customers.getCusName());
                        //jsonUnRead.put("water_read_cycle",customers.getWaterReadCycle());
                        //jsonUnRead.put("unread_times",customers.getUnreadTimes());
                        //jsonUnRead.put("read_times",customers.getReadTimes());
                        //jsonUnRead.put("tenant_id",customers.getTenantId());
                        //recordsService.createOnlineData(unReadCode,jsonUnRead);
                    }
                }
                /**清空所有抄表数据*/
                //初始化 本月待抄表次数数据
                // customersService.update(new LambdaUpdateWrapper<ArcCustomers>()
                //         .set(ArcCustomers::getReadTimes,0)
                //         .set(ArcCustomers::getUnreadTimes,0)
                //         .eq(ArcCustomers::getDelFlag,0)
                //         .eq(ArcCustomers::getWaterUserStatus,"1") //正常
                //     );

                //初始化 本月待抄表次数数据
                customersService.update(new LambdaUpdateWrapper<ArcCustomers>()
                        .set(ArcCustomers::getReadTimes,1)
                        .set(ArcCustomers::getUnreadTimes,1)
                        .eq(ArcCustomers::getDelFlag,0)
                        .eq(ArcCustomers::getWaterUserStatus,"1") //正常
                        .in(ArcCustomers::getWaterReadCycle,readMonth)); //满足本月应抄

                //一月多抄-月初始化
                customersService.mitReadInit();
        //    }
        //}
    }

    @Override
    public List<ArcIndexDataVO> queryArcIndexData() {
        return arcCustomersMapper.queryArcIndexData();
    }

    /***用户状态 1正常2报停3停水4销户*/
    @Override
    @Transactional
    public Result<?> addNotice(JSONObject cusObj) {
        String ids = cusObj.getString("cusIds");
        if(oConvertUtils.isNotEmpty(ids)) {
            for (String id : ids.split(",")) {
                ArcCustomers arcCustomers = arcCustomersMapper.selectById(id);
                if (null != arcCustomers) {
                    if ("1".equals(arcCustomers.getWaterUserStatus())) {
                        arcCustomers.setWaterUserStatus("2");
                        arcCustomers.setNoticeRemark(cusObj.getString("changeCause") + " " + cusObj.getString("noticeRemark"));
                        arcCustomers.setChangeCause(cusObj.getString("changeCause"));
                        arcCustomers.setNoticeTime(new Date());
                        arcCustomersMapper.updateById(arcCustomers);
                        //首页数据更新
                        chgFeesService.indexData(null, null);
                        ;
                        return Result.OK("报停成功");
                    } else {
                        return Result.error("用户当前已不是正常状态，不能报停");
                    }
                }
            }
        }
        return Result.error("用户不存在");
    }

    @Override
    @Transactional
    public Result<?> addStop(JSONObject cusObj) {
        String ids = cusObj.getString("cusIds");
        if(oConvertUtils.isNotEmpty(ids)) {
            for (String id : ids.split(",")) {
                ArcCustomers arcCustomers = arcCustomersMapper.selectById(id);
                if (null != arcCustomers) {
                    if ("1".equals(arcCustomers.getWaterUserStatus())) {
                        arcCustomers.setWaterUserStatus("3");
                        arcCustomers.setStopRemark(cusObj.getString("changeCause") + " " + cusObj.getString("stopRemark"));
                        arcCustomers.setChangeCause(cusObj.getString("changeCause"));
                        arcCustomers.setStopTime(new Date());
                        arcCustomersMapper.updateById(arcCustomers);
                        //首页数据更新
                        chgFeesService.indexData(null, null);
                        ;
                        return Result.OK("停水成功");
                    } else {
                        return Result.error("用户当前已不是正常状态，不能停水");
                    }
                }
            }
        }
        return Result.error("用户不存在");
    }

    @Override
    @Transactional
    public Result<?> addCancel(JSONObject cusObj) {
        String ids = cusObj.getString("cusIds");
        if(oConvertUtils.isNotEmpty(ids)) {
            for (String id : ids.split(",")) {
                ArcCustomers arcCustomers = arcCustomersMapper.selectById(id);
                if (null != arcCustomers) {
                    if ("1".equals(arcCustomers.getWaterUserStatus())) {
                        LambdaQueryWrapper<ChgArrears> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(ChgArrears::getCusId, id);
                        queryWrapper.eq(ChgArrears::getDelFlag, 0);
                        List<ChgArrears> arrearsList = chgArrearsService.list(queryWrapper);
                        if (null != arrearsList && arrearsList.size() > 0) {
                            return Result.error("用户当前存在欠费记录");
                        }
                        arcCustomers.setWaterUserStatus("4");

                        arcCustomers.setCancelRemark(cusObj.getString("changeCause") + " " + cusObj.getString("cancelRemark"));
                        arcCustomers.setChangeCause(cusObj.getString("changeCause"));
                        arcCustomers.setCancelTime(new Date());
                        arcCustomersMapper.updateById(arcCustomers);
                        //首页数据更新
                        chgFeesService.indexData(null, null);
                        ;
                        return Result.OK("销户成功");
                    } else {
                        return Result.error("用户当前已不是正常状态，不能销户");
                    }
                }
            }
        }
        return Result.error("用户不存在");
    }
    @Override
    @Transactional
    public Result<?> addRecover(JSONObject cusObj) {
        String ids = cusObj.getString("cusIds");
        if(oConvertUtils.isNotEmpty(ids)){
            for (String id : ids.split(",")) {
                ArcCustomers arcCustomers = arcCustomersMapper.selectById(id);
                if(null != arcCustomers){
                    if(Integer.parseInt(arcCustomers.getWaterUserStatus()) != 1 ){
                       //不是正常状态，恢复正常状态
                        arcCustomers.setWaterUserStatus("1");
                        arcCustomers.setRecoverRemark(cusObj.getString("changeCause")+" "+cusObj.getString("recoverRemark"));
                        arcCustomers.setChangeCause(cusObj.getString("changeCause"));
                        arcCustomers.setRecoverTime(new Date());

                        //当前月份
                        Calendar calendar = DateUtils.getCalendar();
                        int m = calendar.get(Calendar.MONTH)+1; //从0开始

                        //满足的抄表周期
                        List<String>readMonth=new ArrayList<>();

                        if( m % 6 == 0){
                            //半年
                            readMonth.add("7");
                        }
                        if( m % 3 == 0){
                            //季度下
                            readMonth.add("6");
                        }else if( m % 3 == 2){
                            //季度中
                            readMonth.add("5");
                        }else if( m % 3 == 1){
                            //季度上
                            readMonth.add("4");
                        }

                        if( m % 2 == 0){
                            //双月
                            readMonth.add("3");
                        }else{
                            //单月
                            readMonth.add("2");
                        }
                        //每月
                        readMonth.add("1");

                        if(null != arcCustomers.getWaterReadCycle()){
                            if(readMonth.contains(arcCustomers.getWaterReadCycle())){
                                arcCustomers.setReadTimes(1);
                                arcCustomers.setUnreadTimes(1);
                            }
                        }
                        arcCustomersMapper.updateById(arcCustomers);
                        //首页数据更新
                        chgFeesService.indexData(null,null);;
                        return Result.OK("恢复正常状态成功");
                    }else{
                        return Result.error("用户当前已正常状态");
                    }
                }
            }
        }
        return Result.error("用户不存在");
    }

    @Override
    public Result<?> addBatch(JSONObject cusObj) {

        /**
         * {"isWaterUserStatus":"0","isWaterReadCycle":"0","isNatureId":"0","unreadTimes":"1"
         * ,"isPaidDay":"1","cusIds":"1494954584337010690,1490577682973302786","isUnreadTimes":"0"
         * ,"paidDay":"16","isWaterUseType":"0","isReadTimes":"0","isIsRead":"0"}
         *
         */

        String cusIdStr = cusObj.getString("cusIds");
        String[] cusIds = null;
        if(oConvertUtils.isNotEmpty(cusIdStr)){
            cusIds = cusIdStr.split(",");
        }

        List<ArcCustomers> customersList = customersService.listByIds(Arrays.asList(cusIds));

        LambdaUpdateWrapper<ArcCustomers> updateWrapper = new LambdaUpdateWrapper<>();
        if(oConvertUtils.isNotEmpty(cusObj.getString("waterUserStatus"))){
            updateWrapper.set(ArcCustomers::getWaterUserStatus,cusObj.getString("waterUserStatus"));
        }
        if(oConvertUtils.isNotEmpty(cusObj.getString("waterReadCycle"))){
            updateWrapper.set(ArcCustomers::getWaterReadCycle,cusObj.getString("waterReadCycle"));
        }
        if(oConvertUtils.isNotEmpty(cusObj.getString("natureId"))){
            updateWrapper.set(ArcCustomers::getNatureId,cusObj.getString("natureId"));
        }
        if(oConvertUtils.isNotEmpty(cusObj.getString("paidDay"))){
            updateWrapper.set(ArcCustomers::getPaidDay,cusObj.getInteger("paidDay"));
        }
        if(oConvertUtils.isNotEmpty(cusObj.getString("unreadTimes"))){
            updateWrapper.set(ArcCustomers::getUnreadTimes,cusObj.getInteger("unreadTimes"));
        }
        if(oConvertUtils.isNotEmpty(cusObj.getString("waterUseType"))){
            updateWrapper.set(ArcCustomers::getWaterUseType,cusObj.getString("waterUseType"));
        }
        if(oConvertUtils.isNotEmpty(cusObj.getString("readTimes"))){
            updateWrapper.set(ArcCustomers::getReadTimes,cusObj.getInteger("readTimes"));
        }
        if(oConvertUtils.isNotEmpty(cusObj.getString("isRead"))){
            updateWrapper.set(ArcCustomers::getIsRead,cusObj.getInteger("isRead"));
        }
        updateWrapper.eq(ArcCustomers::getDelFlag,0);
        updateWrapper.in(ArcCustomers::getId,cusIds);
        customersService.update(updateWrapper);

        //用户修改记录-保存 /online/cgformList/402881a9803039020180303902e10000
        String code="402881a9803039020180303902e10000";
        for (ArcCustomers arcCustomers : customersList) {
            if(oConvertUtils.isNotEmpty(cusObj.getString("waterUserStatus"))){
                JSONObject jsonObj=new JSONObject();
                jsonObj.put("cus_id",arcCustomers.getId());
                jsonObj.put("cus_code",arcCustomers.getCode());
                jsonObj.put("cus_name",arcCustomers.getCusName());
                jsonObj.put("old_text",arcCustomers.getWaterUserStatus());
                jsonObj.put("new_text",cusObj.getString("waterUserStatus"));
                sysBaseAPI.createOnlineData(code,jsonObj);
            }

            if(oConvertUtils.isNotEmpty(cusObj.getString("waterReadCycle"))){
                JSONObject jsonObj=new JSONObject();
                jsonObj.put("cus_id",arcCustomers.getId());
                jsonObj.put("cus_code",arcCustomers.getCode());
                jsonObj.put("cus_name",arcCustomers.getCusName());
                jsonObj.put("old_text",arcCustomers.getWaterReadCycle());
                jsonObj.put("new_text",cusObj.getString("waterReadCycle"));
                sysBaseAPI.createOnlineData(code,jsonObj);
            }
            if(oConvertUtils.isNotEmpty(cusObj.getString("natureId"))){
                JSONObject jsonObj=new JSONObject();
                jsonObj.put("cus_id",arcCustomers.getId());
                jsonObj.put("cus_code",arcCustomers.getCode());
                jsonObj.put("cus_name",arcCustomers.getCusName());
                jsonObj.put("old_text",arcCustomers.getNatureId());
                jsonObj.put("new_text",cusObj.getString("natureId"));
                sysBaseAPI.createOnlineData(code,jsonObj);
            }
            if(oConvertUtils.isNotEmpty(cusObj.getString("paidDay"))){
                JSONObject jsonObj=new JSONObject();
                jsonObj.put("cus_id",arcCustomers.getId());
                jsonObj.put("cus_code",arcCustomers.getCode());
                jsonObj.put("cus_name",arcCustomers.getCusName());
                jsonObj.put("old_text",arcCustomers.getPaidDay());
                jsonObj.put("new_text",cusObj.getString("paidDay"));
                sysBaseAPI.createOnlineData(code,jsonObj);
            }
            if(oConvertUtils.isNotEmpty(cusObj.getString("unreadTimes"))){
                JSONObject jsonObj=new JSONObject();
                jsonObj.put("cus_id",arcCustomers.getId());
                jsonObj.put("cus_code",arcCustomers.getCode());
                jsonObj.put("cus_name",arcCustomers.getCusName());
                jsonObj.put("old_text",arcCustomers.getUnreadTimes());
                jsonObj.put("new_text",cusObj.getString("unreadTimes"));
                sysBaseAPI.createOnlineData(code,jsonObj);
            }
            if(oConvertUtils.isNotEmpty(cusObj.getString("waterUseType"))){
                JSONObject jsonObj=new JSONObject();
                jsonObj.put("cus_id",arcCustomers.getId());
                jsonObj.put("cus_code",arcCustomers.getCode());
                jsonObj.put("cus_name",arcCustomers.getCusName());
                jsonObj.put("old_text",arcCustomers.getWaterUseType());
                jsonObj.put("new_text",cusObj.getString("waterUseType"));
                sysBaseAPI.createOnlineData(code,jsonObj);
            }
            if(oConvertUtils.isNotEmpty(cusObj.getString("readTimes"))){
                JSONObject jsonObj=new JSONObject();
                jsonObj.put("cus_id",arcCustomers.getId());
                jsonObj.put("cus_code",arcCustomers.getCode());
                jsonObj.put("cus_name",arcCustomers.getCusName());
                jsonObj.put("old_text",arcCustomers.getReadTimes());
                jsonObj.put("new_text",cusObj.getString("readTimes"));
                sysBaseAPI.createOnlineData(code,jsonObj);
            }
            if(oConvertUtils.isNotEmpty(cusObj.getString("isRead"))){
                JSONObject jsonObj=new JSONObject();
                jsonObj.put("cus_id",arcCustomers.getId());
                jsonObj.put("cus_code",arcCustomers.getCode());
                jsonObj.put("cus_name",arcCustomers.getCusName());
                jsonObj.put("old_text",arcCustomers.getIsRead());
                jsonObj.put("new_text",cusObj.getString("isRead"));
                sysBaseAPI.createOnlineData(code,jsonObj);
            }
        }

        System.out.println(cusObj.toJSONString());

        return Result.OK("修改成功");
    }

    @Override
    public void mitReadInit() {
        this.arcCustomersMapper.mitReadInit();
    }

    @Override
    public Result<?> batchMater(JSONObject materObj) {
        /**
         *  bisNatureId:'',
         *  natureId:'',
         *  bisBookId:'',
         *  bookId:'',
         *  bisWaterReadCycle:'',
         *  waterReadCycle:'',
         *  bisWaterUseType:'',
         *  waterUseType:'',
         *  bisLastReadScale:'',
         *  lastReadScale:'',
         *  bisLastAddress
         *  address
         *  bisIsCalculated:'',
         *  isCalculated:'',
         *  bisIsRead:'',
         *  isRead:'',
         *  bisIsCharged:'',
         *  isCharged:''
         */
        String cusIdStr = materObj.getString("ids");
        String[] cusIds = null;
        if(oConvertUtils.isNotEmpty(cusIdStr)){
            cusIds = cusIdStr.split(",");
        }
        boolean isRun=false;
        boolean isChangesBook=false;

        List<ArcCustomers> customersList = customersService.listByIds(Arrays.asList(cusIds));
        LambdaUpdateWrapper<ArcCustomers> updateWrapper = new LambdaUpdateWrapper<>();

        if(oConvertUtils.isNotEmpty(materObj.getString("bisNatureId"))
                && "1".equals(materObj.getString("bisNatureId"))
            && oConvertUtils.isNotEmpty(materObj.getString("natureId"))
            ){
            isRun=true;
            updateWrapper.set(ArcCustomers::getNatureId,materObj.getString("natureId"));
        }

        if(oConvertUtils.isNotEmpty(materObj.getString("bisBookId"))
                && "1".equals(materObj.getString("bisBookId"))
                && oConvertUtils.isNotEmpty(materObj.getString("bookId"))
            ){
            isRun=true;
            updateWrapper.set(ArcCustomers::getBookId,materObj.getString("bookId"));

            //需要修改 抄表本关联水表
            isChangesBook=true;
        }
        if(oConvertUtils.isNotEmpty(materObj.getString("bisWaterReadCycle"))
                && "1".equals(materObj.getString("bisWaterReadCycle"))
                && oConvertUtils.isNotEmpty(materObj.getString("waterReadCycle"))
            ){
            isRun=true;
            updateWrapper.set(ArcCustomers::getWaterReadCycle,materObj.getString("waterReadCycle"));
        }

        if(oConvertUtils.isNotEmpty(materObj.getString("bisWaterUseType"))
                && "1".equals(materObj.getString("bisWaterUseType"))
                && oConvertUtils.isNotEmpty(materObj.getString("waterUseType"))
            ){
            isRun=true;
            updateWrapper.set(ArcCustomers::getWaterUseType,materObj.getInteger("waterUseType"));
        }
        if(oConvertUtils.isNotEmpty(materObj.getString("bisLastReadScale"))
                && "1".equals(materObj.getString("bisLastReadScale"))
                && oConvertUtils.isNotEmpty(materObj.getString("lastReadScale"))
            ){
            isRun=true;
            updateWrapper.set(ArcCustomers::getLastReadScale,materObj.getInteger("lastReadScale"));
        }
        if(oConvertUtils.isNotEmpty(materObj.getString("bisLastAddress"))
                && "1".equals(materObj.getString("bisLastAddress"))
                && oConvertUtils.isNotEmpty(materObj.getString("address"))
            ){
            isRun=true;
            updateWrapper.set(ArcCustomers::getAddress,materObj.getString("address"));
        }
        if(oConvertUtils.isNotEmpty(materObj.getString("bisManholeId"))
                && "1".equals(materObj.getString("bisManholeId"))
                && oConvertUtils.isNotEmpty(materObj.getString("manholeId"))
            ){
            isRun=true;
            updateWrapper.set(ArcCustomers::getManholeId,materObj.getString("manholeId"));
        }
        if(oConvertUtils.isNotEmpty(materObj.getString("bisIsRead"))
                && "1".equals(materObj.getString("bisIsRead"))
                && oConvertUtils.isNotEmpty(materObj.getString("isRead"))
            ){
            isRun=true;
            updateWrapper.set(ArcCustomers::getIsRead,materObj.getInteger("isRead"));
        }
        if(oConvertUtils.isNotEmpty(materObj.getString("bisIsCalculated"))
                && "1".equals(materObj.getString("bisIsCalculated"))
                && oConvertUtils.isNotEmpty(materObj.getString("isCalculated"))
            ){
            isRun=true;
            updateWrapper.set(ArcCustomers::getReadTimes,materObj.getInteger("readTimes"));
        }
        if(oConvertUtils.isNotEmpty(materObj.getString("bisIsCharged"))
                && "1".equals(materObj.getString("bisIsCharged"))
                && oConvertUtils.isNotEmpty(materObj.getString("isCharged"))
            ){
            isRun=true;
            updateWrapper.set(ArcCustomers::getIsCharged,materObj.getInteger("isCharged"));
        }
        if(isRun){
            updateWrapper.eq(ArcCustomers::getDelFlag,0);
            updateWrapper.in(ArcCustomers::getId,cusIds);
            customersService.update(updateWrapper);
        }

        //用户修改记录-保存 /online/cgformList/402881a9803039020180303902e10000
        String code="402881a9803039020180303902e10000";
        if(isRun) {
            for (ArcCustomers arcCustomers : customersList) {
                if (oConvertUtils.isNotEmpty(materObj.getString("bisNatureId"))
                        && "1".equals(materObj.getString("bisNatureId"))
                        && oConvertUtils.isNotEmpty(materObj.getString("natureId"))
                ) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("cus_id", arcCustomers.getId());
                    jsonObj.put("cus_code", arcCustomers.getCode());
                    jsonObj.put("cus_name", arcCustomers.getCusName());
                    jsonObj.put("old_text", arcCustomers.getNatureId());
                    jsonObj.put("new_text", materObj.getString("natureId"));
                    sysBaseAPI.createOnlineData(code, jsonObj);
                }

                if (oConvertUtils.isNotEmpty(materObj.getString("bisWaterReadCycle"))
                        && "1".equals(materObj.getString("bisWaterReadCycle"))
                        && oConvertUtils.isNotEmpty(materObj.getString("waterReadCycle"))
                ) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("cus_id", arcCustomers.getId());
                    jsonObj.put("cus_code", arcCustomers.getCode());
                    jsonObj.put("cus_name", arcCustomers.getCusName());
                    jsonObj.put("old_text", arcCustomers.getWaterReadCycle());
                    jsonObj.put("new_text", materObj.getString("waterReadCycle"));
                    sysBaseAPI.createOnlineData(code, jsonObj);
                }
                if (oConvertUtils.isNotEmpty(materObj.getString("bisBookId"))
                        && "1".equals(materObj.getString("bisBookId"))
                        && oConvertUtils.isNotEmpty(materObj.getString("bookId"))
                ) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("cus_id", arcCustomers.getId());
                    jsonObj.put("cus_code", arcCustomers.getCode());
                    jsonObj.put("cus_name", arcCustomers.getCusName());
                    jsonObj.put("old_text", arcCustomers.getBookId());
                    jsonObj.put("new_text", materObj.getString("bookId"));
                    sysBaseAPI.createOnlineData(code, jsonObj);
                }
                if (oConvertUtils.isNotEmpty(materObj.getString("bisWaterUseType"))
                        && "1".equals(materObj.getString("bisWaterUseType"))
                        && oConvertUtils.isNotEmpty(materObj.getString("waterUseType"))
                ) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("cus_id", arcCustomers.getId());
                    jsonObj.put("cus_code", arcCustomers.getCode());
                    jsonObj.put("cus_name", arcCustomers.getCusName());
                    jsonObj.put("old_text", arcCustomers.getWaterUseType());
                    jsonObj.put("new_text", materObj.getString("waterUseType"));
                    sysBaseAPI.createOnlineData(code, jsonObj);
                }
                if (oConvertUtils.isNotEmpty(materObj.getString("bisLastReadScale"))
                        && "1".equals(materObj.getString("bisLastReadScale"))
                        && oConvertUtils.isNotEmpty(materObj.getString("lastReadScale"))
                ) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("cus_id", arcCustomers.getId());
                    jsonObj.put("cus_code", arcCustomers.getCode());
                    jsonObj.put("cus_name", arcCustomers.getCusName());
                    jsonObj.put("old_text", arcCustomers.getLastReadScale());
                    jsonObj.put("new_text", materObj.getString("lastReadScale"));
                    sysBaseAPI.createOnlineData(code, jsonObj);
                }
                if(oConvertUtils.isNotEmpty(materObj.getString("bisLastAddress"))
                        && "1".equals(materObj.getString("bisLastAddress"))
                        && oConvertUtils.isNotEmpty(materObj.getString("address"))
                ){
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("cus_id", arcCustomers.getId());
                    jsonObj.put("cus_code", arcCustomers.getCode());
                    jsonObj.put("cus_name", arcCustomers.getCusName());
                    jsonObj.put("old_text", arcCustomers.getAddress());
                    jsonObj.put("new_text", materObj.getString("address"));
                    sysBaseAPI.createOnlineData(code, jsonObj);
                }
                if(oConvertUtils.isNotEmpty(materObj.getString("bisManholeId"))
                        && "1".equals(materObj.getString("bisManholeId"))
                        && oConvertUtils.isNotEmpty(materObj.getString("manholeId"))
                ){
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("cus_id", arcCustomers.getId());
                    jsonObj.put("cus_code", arcCustomers.getCode());
                    jsonObj.put("cus_name", arcCustomers.getCusName());
                    jsonObj.put("old_text", arcCustomers.getAddress());
                    jsonObj.put("new_text", materObj.getString("manholeId"));
                    sysBaseAPI.createOnlineData(code, jsonObj);
                }
                if (oConvertUtils.isNotEmpty(materObj.getString("bisIsRead"))
                        && "1".equals(materObj.getString("bisIsRead"))
                        && oConvertUtils.isNotEmpty(materObj.getString("isRead"))
                ) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("cus_id", arcCustomers.getId());
                    jsonObj.put("cus_code", arcCustomers.getCode());
                    jsonObj.put("cus_name", arcCustomers.getCusName());
                    jsonObj.put("old_text", arcCustomers.getIsRead());
                    jsonObj.put("new_text", materObj.getString("isRead"));
                    sysBaseAPI.createOnlineData(code, jsonObj);
                }
                if (oConvertUtils.isNotEmpty(materObj.getString("bisIsCalculated"))
                        && "1".equals(materObj.getString("bisIsCalculated"))
                        && oConvertUtils.isNotEmpty(materObj.getString("isCalculated"))
                ) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("cus_id", arcCustomers.getId());
                    jsonObj.put("cus_code", arcCustomers.getCode());
                    jsonObj.put("cus_name", arcCustomers.getCusName());
                    jsonObj.put("old_text", arcCustomers.getIsCalculated());
                    jsonObj.put("new_text", materObj.getString("isCalculated"));
                    sysBaseAPI.createOnlineData(code, jsonObj);
                }
                if (oConvertUtils.isNotEmpty(materObj.getString("bisIsCharged"))
                        && "1".equals(materObj.getString("bisIsCharged"))
                        && oConvertUtils.isNotEmpty(materObj.getString("isCharged"))
                ) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("cus_id", arcCustomers.getId());
                    jsonObj.put("cus_code", arcCustomers.getCode());
                    jsonObj.put("cus_name", arcCustomers.getCusName());
                    jsonObj.put("old_text", arcCustomers.getIsCharged());
                    jsonObj.put("new_text", materObj.getString("isCharged"));
                    sysBaseAPI.createOnlineData(code, jsonObj);
                }

                //需要修改 抄表本关联水表
                if(isChangesBook){
                    bookMetersService.update(Wrappers.<MrBookMeters>lambdaUpdate().set(MrBookMeters::getBookId,materObj.getString("bookId"))
                        .eq(MrBookMeters::getCustomerId,arcCustomers.getCode()).eq(MrBookMeters::getDelFlag,0));
                }
            }
        }
        //System.out.println(materObj.toJSONString());

        return Result.OK("批量修改成功");
    }

    @Override
    public String queryNextCode() {
        String nextBianCode ="";
        String tenant = TenantContext.getTenant();
        String key="arc::next::code::"+tenant;
        if(redisUtil.hasKey(key)){
            String maxCode = redisUtil.get(key).toString();
            nextBianCode = YouBianCodeUtil.getNextBianCode("", maxCode, maxCode.length());
        }

        //String maxCode = arcCustomersMapper.queryNextCode();
        //if(oConvertUtils.isNotEmpty(maxCode)){
        //    nextBianCode = YouBianCodeUtil.getNextBianCode("", maxCode, maxCode.length());
        //}else{
        //    nextBianCode = YouBianCodeUtil.getNextBianCode("", "020001", 6);
        //}
        return nextBianCode;
    }

    /**校验必填信息*/
    String checkFormData(JSONObject cusObj){
        String msg="";
        //用户信息
        JSONObject formData1 = (JSONObject) cusObj.get("formData1");
        JSONObject formData2 = (JSONObject) cusObj.get("formData2");
        JSONObject formData3 = (JSONObject) cusObj.get("formData3");
        JSONObject formData4 = (JSONObject) cusObj.get("formData4");

        if(oConvertUtils.isNotEmpty(formData1.getString("contactId"))){

        }else {
            if (oConvertUtils.isEmpty(formData1.getString("name"))
                || oConvertUtils.isEmpty(formData1.getString("address"))
                || oConvertUtils.isEmpty(formData1.getString("mobile"))
                || oConvertUtils.isEmpty(formData1.getString("certificateId"))
            ) {
              msg = "用户信息-必填信息不能为空！";
            }
        }
        if(msg.length()>5){
            return msg;
        }

        if(oConvertUtils.isEmpty(formData2.getString("areaId"))
            || oConvertUtils.isEmpty(formData2.getString("address"))
            || oConvertUtils.isEmpty(formData2.getString("code"))
            || oConvertUtils.isEmpty(formData2.getString("isRemote"))
            || oConvertUtils.isEmpty(formData2.getString("waterUseType"))
            || oConvertUtils.isEmpty(formData2.getString("firstInstallTime"))
            || oConvertUtils.isEmpty(formData2.getString("waterUserStatus"))
        ){
            msg="水表信息-必填信息不能为空！";
        }
        if(msg.length()>5){
            return msg;
        }
        if(oConvertUtils.isEmpty(formData3.getString("natureId"))
            || oConvertUtils.isEmpty(formData3.getString("isCalculated"))
            || oConvertUtils.isEmpty(formData3.getString("isCharged"))
            || oConvertUtils.isEmpty(formData3.getString("isStored"))
            || oConvertUtils.isEmpty(formData3.getString("isVat"))
            || oConvertUtils.isEmpty(formData3.getString("isPreinvoiced"))
            || oConvertUtils.isEmpty(formData3.getString("isTieredPrice"))
        ){
            msg="计费信息-必填信息不能为空！";
        }
        if(msg.length()>5){
            return msg;
        }
        if(oConvertUtils.isEmpty(formData4.getString("waterReadCycle"))
            || oConvertUtils.isEmpty(formData4.getString("isRead"))
            || oConvertUtils.isEmpty(formData4.getString("readTimes"))
            || oConvertUtils.isEmpty(formData4.getString("unreadTimes"))
            || oConvertUtils.isEmpty(formData4.getString("firstScale"))
            || oConvertUtils.isEmpty(formData4.getString("paidDay"))
        ){
            msg="计费信息-必填信息不能为空！";
        }

        return msg;
    }
}
